//
//  CYCallCenter.m
//  CreditAddressBook
//
//  Created by LE on 15/12/3.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYCallCenter.h"
#import <CoreTelephony/CTCall.h>
#import <CoreTelephony/CTCallCenter.h>
#import "CYCallHistory.h"
#import "CYPerson.h"
#import "CYDatabase.h"
#import "CYDialTool.h"
#import "CYABTool.h"
#import "MobClick.h"

static CTCallCenter *_callCenter;
static NSString *_callID;
static NSString *_num;//电话号码
static NSString *_name;//姓名
static CYPerson *_person;

@implementation CYCallCenter

+ (instancetype)sharedCallCenter {
    static CYCallCenter *center = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //创建通话中心
        _callCenter = [[CTCallCenter alloc] init];
        _callCenter.callEventHandler = ^(CTCall *call){};
        
        center = [[CYCallCenter alloc] init];
    });
    return center;
}

/**
 *  拨打电话
 *
 *  @param num     电话号码
 *  @param failure
 */
- (void)callWithNumber:(NSString *)num name:(NSString *)name person:(CYPerson *)person success:(void(^)(void))success failure:(void(^)(void))failure {
    NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@" ,num]];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
    if(!canOpen){//不能打开
        if (failure) {
            failure();
        }
    }
    [[UIApplication sharedApplication] openURL:url];
    
    //获取通话状态
    _num = num;
    _name = name;
    _person = person;
    _callCenter.callEventHandler = ^(CTCall *call) {
        CYLog(@"通话状态：%@", [call description]);
        _callID = call.callID;
        CYCallHistory *callHistory = [[CYCallHistory alloc] init];
        
        if ([call.callState isEqualToString:CTCallStateDialing]) {//呼叫中
            callHistory.callId = _callID;
            callHistory.parentId = @"0";
            callHistory.status = call.callState;
            callHistory.phone = _num;
            callHistory.name = _name;
            callHistory.thumbnail = _person.person.thumbnail;
            callHistory.recordID = _person.person.recordID;
            [[CYDatabase sharedDatabase] addCallHistory:callHistory];
        } else if ([call.callState isEqualToString:CTCallStateIncoming]) {//来电中
            callHistory.callId = _callID;
            callHistory.parentId = @"0";
            callHistory.status = call.callState;
            callHistory.phone = _num;
            callHistory.name = _name;
            callHistory.thumbnail = _person.person.thumbnail;
            callHistory.recordID = _person.person.recordID;
            [[CYDatabase sharedDatabase] addCallHistory:callHistory];
        } else if ([call.callState isEqualToString:CTCallStateConnected]) {//接通
            callHistory.callId = [CYDialTool randomID];
            callHistory.parentId = _callID;
            callHistory.status = call.callState;
            callHistory.phone = _num;
            callHistory.name = _name;
            callHistory.recordID = _person.person.recordID;
            [[CYDatabase sharedDatabase] addCallHistory:callHistory];
        } else if ([call.callState isEqualToString:CTCallStateDisconnected]) {//挂断
            callHistory.callId = [CYDialTool randomID];
            callHistory.parentId = _callID;
            callHistory.status = call.callState;
            callHistory.phone = _num;
            callHistory.name = _name;
            callHistory.recordID = _person.person.recordID;
            
            [[CYDatabase sharedDatabase] addCallHistory:callHistory];
            
            //从数据库获取其他状态，计算通话时长并保存
            BOOL succ = [[CYDatabase sharedDatabase] updateDuration:callHistory];
            
            if (success) {
                if (succ) {
                    CYLog(@"通话记录插入更新成功");
                    
                    [CYABTool jfshopWithType:@"1" success:nil failure:^(NSError *error) {
                        CYLog(@"通话积分添加失败: %@", error);
                    }];
                    
                    //统计通话数
                    [MobClick event:@"call"];
                    dispatch_main_sync_safe_le(^{
                        //更新通话记录显示数据
                        success();
                    });
                }
                
            }
        }
        
    };
}
@end
